package system

import (
	"MoSkeleton/models/base"
	"errors"
	"gorm.io/gorm"
)

type SysUserPost struct {
	UserId uint64 `gorm:"column:user_id;type:BIGINT;NOT NULL"`
	PostId uint64 `gorm:"column:post_id;type:BIGINT;NOT NULL"`
}

func (b *SysUserPost) TableName() string {
	return "sys_user_post"
}

func (b *SysUserPost) AddBatchByUser(tx *gorm.DB, userId uint64, postIds *[]uint64) (bool, error) {
	userPosts := make([]*SysUserPost, 0)
	for _, postId := range *postIds {
		userPosts = append(userPosts, &SysUserPost{
			UserId: userId,
			PostId: postId,
		})
	}
	if len(userPosts) > 0 {
		result := base.GetModelDB(tx).CreateInBatches(userPosts, 100)
		return result.RowsAffected > 0, result.Error
	}
	return true, nil
}

func (b *SysUserPost) DeleteByUserIds(tx *gorm.DB, userIds *[]uint64) (bool, error) {
	result := base.GetModelDB(tx).Where("user_id in (?)", *userIds).Delete(b)
	return result.RowsAffected > 0, result.Error
}

func (b *SysUserPost) DeleteByUserIdsStr(tx *gorm.DB, userIds *[]string) (bool, error) {
	result := base.GetModelDB(tx).Where("user_id in (?)", *userIds).Delete(b)
	return result.RowsAffected > 0, result.Error
}

func (b *SysUserPost) CountUserPostByPostId(postId uint64) (int64, error) {
	var count int64
	result := base.BaseDb.Model(&SysUserPost{}).Where("post_id = ?", postId).Count(&count)
	return count, result.Error
}

func (b *SysUserPost) GetFirstUserPostByPostIds(postIds []uint64) (int64, error) {
	result := base.GetModelDB(nil).Where("post_id in (?)", postIds).First(b)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return 0, nil
	}
	return result.RowsAffected, result.Error
}
